package com.zeus.base.smscenter.restful.api.controller;

import com.alibaba.fastjson.JSON;


import com.google.common.collect.Lists;
import com.wordnik.swagger.annotations.ApiOperation;

import com.zeus.base.privilege.model.TbUser;
import com.zeus.base.privilege.service.IUserService;
import com.zeus.base.smscenter.common.util.DateTimeUtils;
import com.zeus.base.smscenter.common.util.StringUtils;
import com.zeus.base.smscenter.common.validate.ValidateClient;
import com.zeus.base.smscenter.common.validate.model.ValidateStatus;
import com.zeus.base.smscenter.model.SmsLogInfo;
import com.zeus.base.smscenter.model.SmsSupplierProperty;
import com.zeus.base.smscenter.model.Tenant;
import com.zeus.base.smscenter.restful.api.jms.JmsProducer;
import com.zeus.base.smscenter.restful.api.model.ResultModel;
import com.zeus.base.smscenter.restful.api.model.ResultStatus;
import com.zeus.base.smscenter.service.ISmsLogInfoService;

import com.zeus.base.smscenter.service.ISmsSettingService;
import com.zeus.base.smscenter.service.ISupplierPropertyService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 发送短信
 *
 * @author linhaisong
 * @date 2015/12/21.
 */
@RestController
@RequestMapping("/message")
public class MessageController {
    Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private ISmsLogInfoService smsLogInfoService;

    @Autowired
    private ISmsSettingService tenantService;

    @Autowired
    private ISupplierPropertyService smsSupplierPropertyService;

    @Autowired
    private JmsProducer jmsProducer;

    @Autowired
    private IUserService iUserService;

    @RequestMapping(value = "/send", method = RequestMethod.POST)
    @ApiOperation(value = "发送短信")
    public ResponseEntity<ResultModel> findPage(@RequestParam(value = "data") String data) {
        String messageId;
        try {
            SmsLogInfo smsLogInfo = JSON.parseObject(data, SmsLogInfo.class);//校验数据格式
            if(smsLogInfo == null || StringUtils.isEmpty(smsLogInfo.getTenant()) || StringUtils.isEmpty(smsLogInfo.getAuthCenterPassword())){
                return new ResponseEntity(ResultModel.error(ResultStatus.CLIENT_ERROR, "用户名或密码错误"), HttpStatus.OK);
            }
            TbUser user = iUserService.getUserByLoginName(smsLogInfo.getTenant());
            if(user == null){
                return new ResponseEntity(ResultModel.error(ResultStatus.CLIENT_ERROR, "查无此用户"), HttpStatus.OK);
            }
            if(user.getLoginPwd().equals(smsLogInfo.getAuthCenterPassword().toLowerCase()) == false){
                return new ResponseEntity(ResultModel.error(ResultStatus.CLIENT_ERROR, "密码错误"), HttpStatus.OK);
            }
            messageId = jmsProducer.sendMessage("", "", data, smsLogInfo.getTenant() + smsLogInfo.getBizNo());
        } catch (IllegalArgumentException illegalArgumentException) {
            log.error("参数：" + data.toString() + " 参数错误:参数不符合验证规则,error:" + illegalArgumentException.getMessage());
            return new ResponseEntity(ResultModel.error(ResultStatus.CLIENT_ERROR, illegalArgumentException.getMessage()), HttpStatus.OK);
        } catch (NullPointerException nullPointerException) {
            log.error("参数:" + data.toString() + " 参数错误:存在空值,error:" + nullPointerException.getMessage());
            return new ResponseEntity(ResultModel.error(ResultStatus.CLIENT_ERROR, nullPointerException.getMessage()), HttpStatus.OK);
        } catch (Exception exception) {
            log.error("参数:" + data + "系统错误:error:" + exception.getMessage());
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, exception.getMessage()), HttpStatus.OK);
        }
        return new ResponseEntity(ResultModel.ok(messageId), HttpStatus.OK);
    }

    @RequestMapping(value = "/find", method = RequestMethod.POST)
    @ApiOperation(value = "查询短信内容")
    public ResponseEntity<ResultModel> findPageByOperator(@RequestParam(value = "tenant") String tenant,
                                                          @RequestParam(value = "authCenterPassword") String authCenterPassword,
                                                          @RequestParam(value = "begin") String begin,
                                                          @RequestParam(value = "end") String end,
                                                          @RequestParam(value = "data") String data) {
        Date d = new Date();
        log.info(tenant+"进入方法体"+d);
        Map<String, Object> resultMap = null;
        try {
            TbUser user = iUserService.getUserByLoginName(tenant);
            log.info(tenant+"查询用户后"+new Date()+"共使用时间"+(System.currentTimeMillis()-d.getTime()));
            if(user == null){
                return new ResponseEntity(ResultModel.error(ResultStatus.CLIENT_ERROR, "查无此用户"), HttpStatus.OK);
            }
            if(user.getLoginPwd().equals(authCenterPassword.toLowerCase()) == false){
                return new ResponseEntity(ResultModel.error(ResultStatus.CLIENT_ERROR, "密码错误"), HttpStatus.OK);
            }
            Map<String, Object> params = JSON.parseObject(data);
            Integer page = Integer.valueOf(params.get("page").toString());//当前页
            Integer size = Integer.valueOf(params.get("size").toString());//每页显示条数
            
            Object isSearchAllObj = params.get("isSearchAll");
            Boolean isSearchAll = isSearchAllObj == null ? false : (Boolean) isSearchAllObj;//是否查询全部
            if (isSearchAll) {//查询租户下的全部账号
            	Tenant tenantEntity = new Tenant();
                tenantEntity.setHeadCode(tenant);
                List<Map<String, Object>> codeList = tenantService.findByHeadCode(tenantEntity);
                List<String> tenants = Lists.newArrayList();
                if (codeList != null && !codeList.isEmpty()) {
                	for (Map<String, Object> map : codeList) {
                        tenants.add((String) map.get("code"));
                    }
                    params.put("tenants", tenants);
				} else {//查询单个账号
                    params.put("tenant", tenant);
                }
            } else {//查询单个账号
                params.put("tenant", tenant);
            }
            
            if (params.get("bizNos")!=null && !"".equals(params.get("bizNos").toString())) {
				String bizNos = params.get("bizNos").toString();
				String[] bs = bizNos.split(",");
				params.put("bizNos", Arrays.asList(bs));
			}
            params.put("beginDate", DateTimeUtils.toDate(begin, "yyyyMMddHHmmss"));
            params.put("endDate", DateTimeUtils.toDate(end, "yyyyMMddHHmmss"));
            params.put("startIndex", ((page - 1) * size));//开始行
            params.put("pageSize", size);//结束行
            resultMap = smsLogInfoService.find(params);
            log.info(tenant+"返回时间"+new Date()+"共使用时间"+(System.currentTimeMillis()-d.getTime()));
        } catch (Exception exception) {
            log.error("查询短信内容出错", exception);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, exception.getMessage()), HttpStatus.OK);
        }
        return new ResponseEntity(ResultModel.ok(resultMap), HttpStatus.OK);
    }

    @RequestMapping(value = "/findByHeadCode", method = RequestMethod.POST)
    @ApiOperation(value = "查询租户下的所有短信账号")
    public ResponseEntity<ResultModel> findByHeadCode(@RequestParam(value = "tenant") String tenant, String data) {
        List<Map<String, Object>> codeList = null;
        try {
            Tenant tenantEntity = new Tenant();
            tenantEntity.setHeadCode(tenant);
            codeList = tenantService.findByHeadCode(tenantEntity);
        } catch (Exception exception) {
            log.error("查询租户下的所有短信账号", exception);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, exception.getMessage()), HttpStatus.OK);
        }
        return new ResponseEntity(ResultModel.ok(codeList), HttpStatus.OK);
    }

    @RequestMapping(value = "/validate", method = RequestMethod.POST)
    @ApiOperation(value = "验证用户名密码")
    public ResponseEntity<ResultModel> validate(@RequestParam(value = "data") String data) {
        try {
            Map<String, Object> params = JSON.parseObject(data);
            List<SmsSupplierProperty> smsSupplierPropertyList = smsSupplierPropertyService.find(params);
            if (smsSupplierPropertyList == null || smsSupplierPropertyList.isEmpty()) {
                return new ResponseEntity(ResultModel.error(ResultStatus.CLIENT_ERROR, "该租户未查询到对应的用户名密码,请检查租户名是否正确"), HttpStatus.OK);
            }
            String dbUserName = null;//账号
            String dbPassword = null;//密码
            for (SmsSupplierProperty smsSupplierProperty : smsSupplierPropertyList) {
                if (smsSupplierProperty.getPropertyName().equals("loginName")) {
                    dbUserName = smsSupplierProperty.getPropertyValue();
                } else if (smsSupplierProperty.getPropertyName().equals("loginPassword")) {
                    dbPassword = smsSupplierProperty.getPropertyValue();
                }
            }
            params.put("dbUserName", dbUserName);
            params.put("dbPassword", dbPassword);
            ValidateStatus result = ValidateClient.getValidateResult(params);
            if (result.getResult()) {
                return new ResponseEntity(ResultModel.ok(result.getMessage()), HttpStatus.OK);
            } else {
                return new ResponseEntity(ResultModel.error(ResultStatus.CLIENT_ERROR, result.getMessage()), HttpStatus.OK);
            }
        } catch (Exception exception) {
            log.error("查询租户下的所有短信账号", exception);
            return new ResponseEntity(ResultModel.error(ResultStatus.SERVER_ERROR, exception.getMessage()), HttpStatus.OK);
        }
    }

    @RequestMapping(value = "/queryTenantByLoginName", method = RequestMethod.POST)
    @ApiOperation(value = "根据短信平台账号查询租户")
    public ResponseEntity<ResultModel>  queryTenantByLoginName(@RequestParam(value = "data") String data) {
        Map map = JSON.parseObject(data, Map.class);
        if (map == null || map.get("sendType") == null || "".equals(map.get("sendType")) || map.get("loginName") == null || "".equals(map.get("loginName"))) {
            log.error("参数：" + data.toString() + " 参数错误:参数不符合验证规则,error:");
            return new ResponseEntity(ResultModel.error(ResultStatus.CLIENT_ERROR, "缺少必要参数!"), HttpStatus.OK);
        }
        List list = smsSupplierPropertyService.findTenantCodeByDefaultSupplierNoAndLoginName(map);
        return new ResponseEntity(ResultModel.ok(list), HttpStatus.OK);
    }

    @RequestMapping(value = "/querySMSAccountByTenant", method = RequestMethod.POST)
    @ApiOperation(value = "根据租户查询短信平台账号名")
    public ResponseEntity<ResultModel>  querySMSAccountByTenant(@RequestParam(value = "data") String data) {
        Map<String,String> map = JSON.parseObject(data, Map.class);
        if (map == null || map.get("tenant") == null || "".equals(map.get("tenant")) || map.get("authCenterPassword") == null || "".equals(map.get("authCenterPassword"))) {
            log.error("参数：" + data.toString() + " 参数错误:参数不符合验证规则,error:");
            return new ResponseEntity(ResultModel.error(ResultStatus.CLIENT_ERROR, "缺少必要参数!"), HttpStatus.OK);
        }
        TbUser user = iUserService.getUserByLoginName(map.get("tenant"));
        if(user == null){
            return new ResponseEntity(ResultModel.error(ResultStatus.CLIENT_ERROR, "查无此用户"), HttpStatus.OK);
        }
        if(user.getLoginPwd().equals(map.get("authCenterPassword").toLowerCase()) == false){
            return new ResponseEntity(ResultModel.error(ResultStatus.CLIENT_ERROR, "密码错误"), HttpStatus.OK);
        }
        List<Map> list = smsSupplierPropertyService.findLoginNameByTenantCode(map.get("tenant").toString());
        Map resMap = new HashMap();
        resMap.put("smsAccount","");
        resMap.put("voiceAccount","");
        for(int i = 0; i < list.size(); i++){
            if (list.get(i).get("default_sms_supplier_no").equals(list.get(i).get("supplier_no"))) {
                resMap.put("smsAccount",list.get(i).get("property_value"));
            }
            if (list.get(i).get("default_voice_supplier_no").equals(list.get(i).get("supplier_no"))) {
                resMap.put("voiceAccount",list.get(i).get("property_value"));
            }
        }
        return new ResponseEntity(ResultModel.ok(resMap), HttpStatus.OK);
    }
}

